package com.imooc.oauth2.server.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.imooc.commons.model.domain.ResultInfo;
import com.imooc.commons.model.domain.SignInIdentity;
import com.imooc.commons.model.vo.SignInDinerInfo;
import com.imooc.commons.utils.ResultInfoUtil;

import cn.hutool.core.bean.BeanUtil;

/**
 * \* @author: bear
 * \* Date: 2021-07-11-17:17
 * \* describe:
 */
@RestController
public class UserController {
	@Resource
	private HttpServletRequest request;
	@Resource
	private RedisTokenStore redisTokenStore;

	@GetMapping("user/me")
	public ResultInfo getCurrentUser(Authentication authentication){
		//获取用户信息
		SignInIdentity signInIdentity = (SignInIdentity)authentication.getPrincipal();
		//转为前端对象
		SignInDinerInfo signInDinerInfo = new SignInDinerInfo();
		BeanUtil.copyProperties(signInIdentity,signInDinerInfo);
		return ResultInfoUtil.buildSuccess(request.getServletPath(),signInDinerInfo);
	}

	/**
	 * 安全退出
	 *
	 * @param access_token
	 * @param authorization
	 * @return
	 */
	@GetMapping("user/logout")
	public ResultInfo logout(String access_token,String authorization){
		// 判断 access_token 是否为空，为空将 authorization 赋值给 access_token
		if(StringUtils.isBlank(access_token)){
			access_token = authorization;
		}
		// 判断 authorization 是否为空
		if(StringUtils.isBlank(access_token)){
			return ResultInfoUtil.buildSuccess(request.getServletPath(),"退出成功");
		}
		// 判断 bearer token 是否为空
		if(access_token.toLowerCase().contains("bearer ".toLowerCase())){
			access_token = access_token.toLowerCase().replace("bearer ", "");
		}
		//清除redis token信息
		OAuth2AccessToken auth2AccessToken = redisTokenStore.readAccessToken(access_token);
		if(auth2AccessToken != null){
			redisTokenStore.removeAccessToken(auth2AccessToken);
			OAuth2RefreshToken refreshToken = auth2AccessToken.getRefreshToken();
			redisTokenStore.removeRefreshToken(refreshToken);
		}
		return ResultInfoUtil.buildSuccess(request.getServletPath(), "退出成功");
	}
}
